﻿using FrameworkCore.Constants;
using FrameworkCore.Extensions;
using FrameworkCore.Modules.Startups;
using FrameworkCore.Mvc;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using NM.Module.Swagger.Configurations;

namespace NM.Module.Swagger;

/// <summary>
/// 接口文档
/// </summary>
public partial class NetModulerStartup : INetModulerStartup, IRouteProvider
{
    public int Order => 2001;

    public int Priority => Order;

    public void Configure(IApplicationBuilder application)
    {
        var isSwaggerEnabled = ConfigurationsExtensions.GetModulesSection<bool>(nameof(SwaggerSettings.Enabled), SwaggerSettings.Key);
        if (isSwaggerEnabled)
        {
            application.UseSwagger();
            application.UseSwaggerUI();
        }
    }

    public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
    {
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "开发框架", Version = "v1.0" });

            c.CustomOperationIds(apiDesc =>
            {
                var controllerAction = apiDesc.ActionDescriptor as ControllerActionDescriptor;
                return controllerAction!.ControllerName + "-" + controllerAction.ActionName;
            });

            c.CustomSchemaIds(type => type.FullName);

            var modulesDirectory = ApplicationPartManagerExtensions.GetModulesDirectory();
            foreach (var moduleAssemblyFile in Directory.EnumerateFiles(modulesDirectory, "*.xml"))
            {
                string fileName = Path.GetFileName(moduleAssemblyFile);
                if (fileName.StartsWith(GlobalConstants.ModulePrefix, StringComparison.OrdinalIgnoreCase)) // 忽略大小写比较
                {
                    c.IncludeXmlComments(Path.Combine(modulesDirectory, $"{fileName}"), true);
                }
            }

            c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{AppDomain.CurrentDomain.FriendlyName}.xml"), true);
            c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{GlobalConstants.ApplicationKey}.xml"), true);
            c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{GlobalConstants.DomainKey}.xml"), true);
            c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{GlobalConstants.FrameworkCoreKey}.xml"), true);
            c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{GlobalConstants.InfrastructureKey}.xml"), true);

            // 添加授权定义
            c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
            {
                Description = "JWT Authorization header using the Bearer scheme",
                Name = "Authorization",
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.ApiKey
            });
            // 应用授权要求到操作上
            c.AddSecurityRequirement(new OpenApiSecurityRequirement
            {
                {
                    new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference
                        {
                            Type = ReferenceType.SecurityScheme,
                            Id = "Bearer"
                        }
                    },
                    new string[] {}
                }
            });
        });
    }

    public void RegisterRoutes(IEndpointRouteBuilder endpointRouteBuilder)
    {
        endpointRouteBuilder.MapOpenApi();
    }
}
